import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  DatePicker,
  Table,
  Radio,
  Input,
  Icon,
  Tabs,
  Empty
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find'
import {ellipsis,afterCloseModal,todayLastSecond} from '@/utils/utils';
import request from '@/utils/request';
const FormItem = Form.Item;
const { confirm } = Modal;
const { TabPane } = Tabs;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({devices, loading}) => ({
  devices,
  loading: loading.models.devices,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'device_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'device_delete'}),
      showPasswordBtn: find(this.permissions, {name: 'user_default_password_edit'}),
      user_password_reset: find(this.permissions, {name: 'user_password_reset'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      tabBoxHeight:0
    };
  }


  componentDidMount() {

    const {dispatch} = this.props;
    const {
      devices: {detail},
    } = this.props;
    const that=this
    console.log('detail.pageLoaded', detail.pageLoaded)
    const table = document.querySelector('.ant-table-body')
    if (detail.pageLoaded) {
      setTimeout(() => {
        // table.scrollTop = scrollData.y;
        // table.scrollLeft = scrollData.x;
      }, 0)

    } else {
      dispatch({
        type: 'devices/fetchDetail',
        callback: ()=> {
          const {dispatch} = this.props;
          dispatch({
            type: 'devices/changeDetailLoaded',
          })

        }
      });
    }
    this.setState({
      tabBoxHeight:document.querySelector('.custom-card').getBoundingClientRect().bottom-202
    },function(){
      this.changeTableY()
    })

    window.addEventListener('resize', this.resize)
  }

  scroll = (e)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'devices/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop
      },
    })
  }

  resize = ()=> {
    this.changeTableY()
  }

  changeTableY = ()=> {
    console.log('change tableY');

    this.setState({
      tableY: this.state.tabBoxHeight - 150
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)

  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'devices/fetchDetail',
      payload: {
        ...values,
      },
      callback () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      devices: {detail:{searchParams2:searchParams}},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="状态">
          {getFieldDecorator('status',{
            initialValue: searchParams.status,
          })(
            <RadioGroup>
              <RadioButton value="0">全部</RadioButton>
              <RadioButton value="1">上线</RadioButton>
              <RadioButton value="-1">下线</RadioButton>
            </RadioGroup>
          )}
        </FormItem>
        <FormItem label={'开始时间'}>
          {getFieldDecorator('started_at', {
            initialValue: moment(searchParams.started_at),
          })(
            <DatePicker
              showTime
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD HH:mm:ss"
            />
          )}
        </FormItem>
        <FormItem label={'结束时间'}>
          {getFieldDecorator('ended_at', {
            initialValue: moment(searchParams.ended_at),
          })(
            <DatePicker
              showTime
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD HH:mm:ss"
            />
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={()=> {
              const {form} = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  started_at: moment(fieldsValue.started_at).format("YYYY-MM-DD HH:mm:ss"),
                  ended_at: moment(fieldsValue.ended_at).format("YYYY-MM-DD HH:mm:ss"),
                })

              });
            }}
          >
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      started_at:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss"),
      ended_at:todayLastSecond(),
      status:'0',
      page: 1,
      per_page: 20,
    })
  }
  commonCommand = (type) => {
    console.log('type', type);
    const that = this;
    const {
      devices: {detail},
    } = this.props;
    const { dispatch } = this.props;
    request(`/devices/${detail.detailId}/${type}`, {
      method: 'POST',
    }).then((response) => {
      if (response.status === 200) {
        console.log('操作成功');
        if (response.data.task_id) {
          dispatch({
            type: 'global/changeTaskId',
            payload: response.data.task_id,
          });
        }
        window.modal = Modal.success({
          content: '操作成功,正在下发指令...',
          icon:<Icon type="sync" spin />,
          centered:true,
          className:'hideCancel',
          onCancel:()=>{
            return null
          }
        });
      }

    });
  };
  render() {
    const that=this;
    console.log(this.state.tableY)
    const {
      devices: {detail,loading},
    } = this.props;
    const columns = [
      {
        title: '创建时间',
        width: 200,
        dataIndex: 'created_at',
        render: (val, record)=> ellipsis(val, 200)
      },
      {
        title: '状态',
        dataIndex: 'status',

        render(val) {
          let type=""; let color=""; let text="";
          switch (val){
            case -1:
              type="close-circle", color="#eb2f96", text="下线";
              break
            case 1:
              type="check-circle", color="#52c41a", text="上线";
              break
            default:
              break
          }
          return  <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color} />{text}</Fragment>
        },
      },

    ];
    return <div className="custom-card">
      <div className="table-title"><span className={'click-tag'} onClick={()=>{
        console.log('click')
        const {dispatch} = this.props;
        dispatch({
          type: `devices/changeIsDetail`,
          payload: {id:''},
        });
        dispatch({
          type: `devices/resetDetail`,
          payload: false,
        });
      }}>设备列表</span> > {detail.detailId}</div>
      <div style={{padding:'0'}} className="table-page">
        <Tabs className={'detail-tab'}  activeKey={detail.activeKey} onChange={(e)=>{
          console.log('e',e)
          const {dispatch} = this.props;
          dispatch({
            type: `devices/changeDetailActive`,
            payload: e,
            callback:()=>{
              if(e==='2'){
                that.changeTableY()
              }

            }
          });

        }}>
          <TabPane tab="设备资源列表" key="1" forceRender={true}>
            {
              detail.data1.length===0&& <Empty  image={Empty.PRESENTED_IMAGE_SIMPLE}  style={{marginTop:'35px'}}/>
            }
            {
              detail.data1.map((item,index)=>{
                return  <div key={index} className={styles.objItem}>
                  <h2>对象ID : {item.object_id}</h2>
                  {
                    item.instances.map((item2,index2)=>{
                      return <div key={index2}>
                        <h3>实例ID : {item2.instance_id}</h3>
                        <h3 style={{display:'inline-block'}}>资源ID列表 : </h3>{
                        item2.resources.map((item3,index3)=>{
                          return   <Tag  style={{fontSize:'16px',margin:'0 5px 0 0'}} color="geekblue" key={index3}>{item3}</Tag>
                        })
                      }
                      </div>
                    })
                  }
                </div>
              })
            }
          </TabPane>
          <TabPane tab="上下线日志列表" key="2" forceRender={true}>
            <div style={{padding:'15px',height:this.state.tabBoxHeight+"px"}} >
              <div className="table-condition">{this.renderSimpleForm()}</div>
              <Table
                style={{color: '#fff'}}
                className="custom-small-table"
                loading={loading}
                rowKey="id"
                dataSource={ detail.data2}
                columns={columns}
                pagination={false}
                size="small"
                scroll={{x: true, y: this.state.tableY }}
              />
              <div className="table-pagination">
                <MyPagination searchCondition={{...detail.searchParams2}} meta={detail.meta2} handleSearch={this.handleSearch} />
              </div>
            </div>

          </TabPane>
          <TabPane tab="设备操作" key="3" forceRender={true}>
            <div style={{padding:'15px',height:this.state.tabBoxHeight+"px"}} >
              <Form.Item
                style={{marginBottom:'10px'}}
              >
                <Button type='primary' onClick={() => {
                  confirm({
                    title: '确定要重启吗?',
                    okText: '确定',
                    centered: true,
                    maskClosable: true,
                    okType: 'primary',
                    cancelText: '取消',
                    onOk() {
                      that.commonCommand('reboot');
                    },
                  });
                }}>重启设备</Button>
              </Form.Item>
              <Form.Item
              >
                <Button style={{marginRight:'10px'}} type='primary' onClick={() => {
                  confirm({
                    title: '确定要开阀吗?',
                    okText: '确定',
                    centered: true,
                    maskClosable: true,
                    okType: 'primary',
                    cancelText: '取消',
                    onOk() {
                      that.commonCommand('open_valve');
                    },
                  });
                }}>设备开阀</Button>
                <Button type='danger' onClick={() => {
                  confirm({
                    title: '确定要关阀吗?',
                    okText: '确定',
                    centered: true,
                    maskClosable: true,
                    okType: 'primary',
                    cancelText: '取消',
                    onOk() {
                      that.commonCommand('close_valve');
                    },
                  });
                }}>设备关阀</Button>
              </Form.Item>
            </div>

          </TabPane>
        </Tabs>

      </div>
    </div>
  }
}

export default BasicList;
